package com.itheima.mq;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RecommendMovementTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 定时读取大数据推荐到redis中的数据转存打mongo中
     */
    @Scheduled(cron = "0/5 * * * * *")
    public void run() {
        Set<String> keys = stringRedisTemplate.keys(ConstantUtil.QUANZI_MOVEMENT + "*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                //获取value
                String value = stringRedisTemplate.opsForValue().get(key);
                //根据逗号进行分割推荐动态的pid
                String[] pids = value.split(",");
                if (pids != null) {
                    //获取用户id
                    Long userId = Long.valueOf(key.replaceAll(ConstantUtil.QUANZI_MOVEMENT, ""));
                    //1.删除原来的数据mongo 2.删除redis (保留mongo数据)  根据需求来
                    Query removeQuery = new Query(
                            Criteria.where("userId").is(userId)
                    );
                    //删除历史数据
                    mongoTemplate.remove(removeQuery, RecommendMovement.class);
                    //循环遍历pids
                    for (String pid : pids) {
                        //根据pid查询动态信息
                        Query query = new Query(Criteria.where("pid").is(Long.valueOf(pid)));
                        Movement movement = mongoTemplate.findOne(query, Movement.class);
                        //将movement转换为recommendMovement
                        RecommendMovement recommendMovement = new RecommendMovement();
                        recommendMovement.setCreated(movement.getCreated());
                        recommendMovement.setPid(Long.valueOf(pid));
                        recommendMovement.setPublishId(movement.getId());
                        recommendMovement.setUserId(userId);
                        recommendMovement.setScore(RandomUtil.randomDouble(66, 99));
                        mongoTemplate.save(recommendMovement);
                    }
                }

            }
        }
    }
}
